//
//  Cwg_ganlan_vc.m
//  ainkjj
//
//  Created by MAX on 2020/4/20.
//  Copyright © 2020 zhiyiLiu. All rights reserved.
//

#import "Cwg_ganlan_vc.h"
#import "Jiankang_fenxi_vc.h"
#import "Huati_taolun_fabu_vc.h"
#import "Huati_guangchang_vc.h"
#import "Tuijian_vc.h"
#import "Tiezi_fabu_vc.h"
#import "Tiezi_xiangqing_vc.h"
#import "Tiezi_pinglun_vc.h"


#import "App_devices_model.h"
#import "BB_bed_Info.h"
#import "Bmi_setBabyBmi.h"
#import "Gailan_grid_sub_view.h"
#import "CYLPlusDemoChildViewController.h"
#import "Music_page_list_vc.h"
#import "PetsAppGetDateCount_res.h"
#import "ASDayPicker.h"
#import "NSDate+YYAdd.h"

#import <JhtMarquee/JhtVerticalMarquee.h>
#import "EventList_res.h"
#import "Shijian_add_vc.h"
#import "GailanPagerVc.h"

static CGFloat const kLeftInset = 16;

@interface Cwg_ganlan_vc ()<Jiankang_fenxi_delegate>
@property (nonatomic, strong)JhtVerticalMarquee *verticalMarquee;

@property (nonatomic, strong)  ASDayPicker *dayPicker;
@property (nonatomic, strong)UILabel *shijianlb;
@property (nonatomic, strong)UILabel *yuelb;
@property (nonatomic, strong)UIScrollView *sv;

@property(nonatomic, strong) QMUIPopupMenuView *popupByWindow;
@property(nonatomic, strong) QMUIButton *shebei_caidan_btn;


@property(nonatomic, strong) QMUIGridView *gridView;
@property (nonatomic, strong)QMUILabel *wenxintishiLb;
@property (nonatomic, strong)App_devicesData *currentDevice;
@property (nonatomic, strong)BB_bed_Info *current_bb_bed_info;
@property (nonatomic, strong)Bmi_setBabyBmi *current_bmi;

@property (nonatomic, strong)UILabel *bb_title_lb;
@property (nonatomic, strong)UILabel *bb_st_lb;
@property (nonatomic, strong)UILabel *bb_xq_lb;
@property (nonatomic, strong)UILabel *shuimian_shichang_lb;
@property (nonatomic, strong)QMUIButton *add_device_btn;


@property (nonatomic, strong)QMUIButton *qu_geng_xin_btn;

@property (nonatomic, strong)PetsAppGetDateCount_res *petsres;
@property (nonatomic, strong)UILabel *cwgwendu_lb;
@property (nonatomic, strong)UILabel *shidu_lb;
@end

@implementation Cwg_ganlan_vc
- (void)dealloc{
    [self.verticalMarquee removeFromSuperview];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    NSDate *day = change[NSKeyValueChangeNewKey];
    //    self.selectedDayLabel.text =  [NSDateFormatter localizedStringFromDate:day dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.yuelb.attributedText = [Anktool stringWithNum:@(day.month).stringValue fontSize:26 color:UIColor.blackColor text:@"月" textFontSize:14 textColor:UIColor.blackColor numFirst:YES];
        NSArray *soureArray = @[@"没有提醒事项哦~"];
        
        //    self.verticalMarquee.isCounterclockwise = YES;
        self.verticalMarquee.sourceArray = soureArray;
    });
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:app_code forKey:@"app_code"];
    [dict setObject:[NSString stringWithFormat:@"%ld-%ld", day.year, day.month] forKey:@"month"];
    //sender.userInteractionEnabled = NO;
    
    [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"Authorization"];
    
    [PPHTTPRequest req:@"api/pets/App/getEventList" parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
//            #import "EventList_res.h"
            NSMutableArray *soureArray = @[].mutableCopy;
            EventList_res *model = [EventList_res mj_objectWithKeyValues:response];
            
            for (EventList_resList *l in model.data.list) {
                
                
                // 创建日历对象
                NSCalendar *calendar = [NSCalendar currentCalendar];
                
                // 获取当前时间
                NSDate *currentDate = day;
                
                // 获取当前时间的年、月、日。利用日历
                NSDateComponents *components = [calendar components:NSCalendarUnitYear| NSCalendarUnitMonth|NSCalendarUnitDay fromDate:currentDate];
                NSInteger currentYear = components.year;
                NSInteger currentMonth = components.month;
                NSInteger currentDay = components.day;
                
                // 获取消息发送时间的年、月、日
                NSDate *msgDate = [NSDate dateWithTimeIntervalSince1970:l.date_time];
                components = [calendar components:NSCalendarUnitYear| NSCalendarUnitMonth|NSCalendarUnitDay fromDate:msgDate];
                CGFloat msgYear = components.year;
                CGFloat msgMonth = components.month;
                CGFloat msgDay = components.day;
                
                // 进行判断
//                NSDateFormatter *dateFmt = [[NSDateFormatter alloc] init];
                if (currentYear == msgYear && currentMonth == msgMonth && currentDay == msgDay) {
                    //今天
                    [soureArray addObject:l.content];
                }
                
            }
            if (soureArray.count == 0) {
                [soureArray addObject:@"没有提醒事项哦~"];
            }
            self.verticalMarquee.sourceArray = soureArray;
        }
        else{
            [QMUITips showError:response[@"error_msg"]];
        }
        
    } failure:^(NSError *error) {
        [QMUITips showError:[error localizedDescription]];
        
    }];
}
- (void)addshijianAction{
        // 添加事件
    Shijian_add_vc *vc= [[Shijian_add_vc alloc]init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    // 请求数据
    [self req_devices];
    
    [self.verticalMarquee marqueeOfSettingWithState:MarqueeContinue_V];
    [self.dayPicker setSelectedDate:[self.dayPicker dateWithoutTimeFromDate:NSDate.date]];

//    [self presentPanModal:[Music_page_list_vc new]];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    // 关闭跑马灯
    [self.verticalMarquee marqueeOfSettingWithState:MarqueePause_V];
}
- (void)setCurrentDevice:(App_devicesData *)currentDevice{
    _currentDevice = currentDevice;
    
    if (currentDevice.device_id == nil) {
        [self.shebei_caidan_btn setTitle:@"无设备" forState:UIControlStateNormal];
        self.bb_xq_lb.text = @"您还未添加设备";
        self.add_device_btn.hidden = NO;
        self.current_bb_bed_info = nil;
        self.current_bmi = nil;
    }else{
        // 请求新的bmi和bed 数据
        self.bb_xq_lb.text = @"您的宝宝基本信息还未添加，为更好掌握宝宝健康状况，请及时添加！";

        [self.shebei_caidan_btn setTitle:currentDevice.device_name forState:UIControlStateNormal];
        [self req];
    }
}
- (void)req{
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:app_code forKey:@"appCode"];
    [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"Authorization"];
    [dict setObject:self.currentDevice.device_id forKey:@"device_id"];
    
    //sender.userInteractionEnabled = NO;
    
    
    [PPHTTPRequest req:@"api/pets/App/getDateCount" parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {

            PetsAppGetDateCount_res *bb_bed_info = [PetsAppGetDateCount_res mj_objectWithKeyValues:response];
            self.petsres = bb_bed_info;
            
        }
        else{
            
            
            [QMUITips showError:response[@"error_msg"] ];
            
        }
        
    } failure:^(NSError *error) {
        [QMUITips showError:[error localizedDescription]];
        
    }];
    
    
   
}
- (void)setPetsres:(PetsAppGetDateCount_res *)current_bb_bed_info{
    _petsres = current_bb_bed_info;
    
    // 睡眠呵护与温馨提示
    
    
    NSMutableArray *cishuAttr = [NSMutableArray array];
    NSMutableArray *shijianArr = NSMutableArray.new;
    
    

    if (current_bb_bed_info.data == nil) {
        if (self.currentDevice) {
            self.wenxintishiLb.text = @"暂无数据";
        }else{
            self.wenxintishiLb.text = @"您还未添加设备";

        }
        shijianArr = @[@"", @""].mutableCopy;
        
        [cishuAttr addObject:[Anktool begin:@"喂水  " begin_fontSize:14 begin_color:rgb(51,51,51) cishu_num:@(0).stringValue cishu_numFontSize:18 cishu_num_textColor:rgb(5,228,189) shegnjiang_img:@""]];

        [cishuAttr addObject:[Anktool begin:@"消毒  " begin_fontSize:14 begin_color:rgb(51,51,51) cishu_num:@(0).stringValue cishu_numFontSize:18 cishu_num_textColor:rgb(5,228,189) shegnjiang_img:@""]];

      
        
    }else{
        
        self.wenxintishiLb.text = _petsres.data.info.tips;
        
        
        
        
        {
            UIColor *textColor = rgb(5,228,189);
            NSString *imgName = @"";
            

            [cishuAttr addObject:[Anktool begin:@"喂水  " begin_fontSize:14 begin_color:rgb(51,51,51) cishu_num:@(current_bb_bed_info.data.info.drinking_count).stringValue cishu_numFontSize:18 cishu_num_textColor:textColor shegnjiang_img:imgName]];
            
        }
        
        {
            UIColor *textColor = rgb(5,228,189);
            NSString *imgName = @"";
            [cishuAttr addObject:[Anktool begin:@"消毒  " begin_fontSize:14 begin_color:rgb(51,51,51) cishu_num:@(current_bb_bed_info.data.info.sterilize_count).stringValue cishu_numFontSize:18 cishu_num_textColor:textColor shegnjiang_img:imgName]];
            
        }
        
        
    }
    
    for (NSInteger i = 0; i < self.gridView.subviews.count; i++) {
        Gailan_grid_sub_view *view = self.gridView.subviews[i];
        
        view.cishuLb.attributedText = cishuAttr[i];
//        DLog(@"%@%@", shijianArr[i], cishuAttr[i]);
    }
    
    self.cwgwendu_lb.text = [NSString stringWithFormat:@"温度\n----\n%.1f℃", self.petsres.data.info.tempera_cabinet];
    self.shidu_lb.text = [NSString stringWithFormat:@"湿度\n----\n%.1f%%", self.petsres.data.info.humidity_cabinet ];
    self.wenxintishiLb.frame = CGRectMake(kLeftInset, CGRectGetMaxY(self.gridView.frame)   + kLeftInset + 30 , self.gridView.mj_w, QMUIViewSelfSizingHeight);
    [self.sv setContentSize:CGSizeMake(ScreenWidth, CGRectGetMaxY(self.wenxintishiLb.frame) + 20)];
}


- (void)req_devices{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:app_code forKey:@"app_code"];
    [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"Authorization"];
    [dict setObject:self.category_id forKey:@"category_id"];

    [PPHTTPRequest req:@"api/App/devices" parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
            App_devices_model *data = [App_devices_model mj_objectWithKeyValues:response];
            if (data.data.count > 0) {
                
                // 更新菜单
                NSMutableArray *arr = NSMutableArray.new;
                for (App_devicesData *aDev in data.data) {
                    QMUIPopupMenuButtonItem *it = [QMUIPopupMenuButtonItem itemWithImage:nil title:aDev.device_name handler:^(QMUIPopupMenuButtonItem *aItem) {
                        [aItem.menuView hideWithAnimated:YES];
                        if (![aItem.deviceId isEqualToString:self.currentDevice.device_id]) {
                            
                            for (App_devicesData *d in data.data) {
                                if ([d.device_id isEqualToString:aItem.deviceId]) {
                                    self.currentDevice = d;
                                    [self.shebei_caidan_btn setTitle:d.device_name forState:UIControlStateNormal];
                                }
                            }
                            
                        }
                    }];
                    it.deviceId = aDev.device_id;
                    [arr addObject:it];
                }
                
                self.popupByWindow.items = arr;
                
                
                // 之前的设备还在吗
                
                for (App_devicesData *aDev in data.data) {
                    if ([self.currentDevice.device_id isEqualToString:aDev.device_id]) {
                        self.currentDevice = aDev;
                        return;
                    }
                }
                
                // 之前的不在了
                
                self.currentDevice = data.data.firstObject;
                

            }else{
                
                self.currentDevice = nil;
                self.popupByWindow.items = @[];

            }
            
           
        }
        
        else
            //            if ([error_code isEqualToString:@""])
        {
            
            [MBProgressHUD showTipMessageInView:response[@"error_msg"]];
            
        }
    } failure:^(NSError *error) {
        [MBProgressHUD showTipMessageInView:[error localizedDescription]];
        
    }];
}
- (void)req_bb_bed{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:app_code forKey:@"appCode"];
    [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"token"];
    [dict setObject:self.currentDevice.device_id forKey:@"deviceId"];
    
    //sender.userInteractionEnabled = NO;
    
    
    [PPHTTPRequest req:@"java/app/device/getBabySleepInfo" parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
            BB_bed_Info *bb_bed_info = [BB_bed_Info mj_objectWithKeyValues:response];
            self.current_bb_bed_info = bb_bed_info;
            
        }
        else{
            
            
            [QMUITips showError:response[@"error_msg"] ];
            
        }
        
    } failure:^(NSError *error) {
        [QMUITips showError:[error localizedDescription]];
        
    }];
}
- (void)req_bmi_info{
    
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:app_code forKey:@"appCode"];
    [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"token"];
    [dict setObject:self.currentDevice.device_id forKey:@"deviceId"];
    
    //sender.userInteractionEnabled = NO;
//    __block QMUITips *qmui_tip = [QMUITips showLoading:@"请求中..." inView:self.navigationController.view];
    
    [PPHTTPRequest req:@"java/app/bmi/getBabyBmi" parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
            
            self.current_bmi = [Bmi_setBabyBmi mj_objectWithKeyValues:response];
            
            
            
        }
        else{
            
            
            [QMUITips showError:response[@"error_msg"]];
            
        }
        
    } failure:^(NSError *error) {
        [QMUITips showError:[error localizedDescription] ];
        
    }];
}


- (void)initSubviews{
    [super initSubviews];
    
    GailanPagerVc *pvc = (GailanPagerVc *)self.parentViewController;
    
    UIScrollView *sv = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight -  Lzy_TabbarHeight - pvc.titleLb_maxY - 44)];
    
    self.view.backgroundColor = RGBA(247,247,247, 1);
    [self.view addSubview:sv];
    sv.backgroundColor = self.view.backgroundColor;
    self.sv = sv;
    [self.sv setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];

    // 婴儿床 菜单
    
    
    self.shebei_caidan_btn = [QDUIHelper generateLightBorderedButton];
    [self.shebei_caidan_btn addTarget:self action:@selector(handleButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self.shebei_caidan_btn setTitle:@"无设备" forState:UIControlStateNormal];
    [self.shebei_caidan_btn setImage:UIImageMake(@"main_drop_down_icon") forState:UIControlStateNormal];
    [self.shebei_caidan_btn setImagePosition:QMUIButtonImagePositionRight];
    [self.shebei_caidan_btn setSpacingBetweenImageAndTitle:4];
    [sv addSubview:self.shebei_caidan_btn];
    
    self.shebei_caidan_btn.frame = CGRectMake(kLeftInset, 10 , 120, 40);
    
    __weak __typeof(self) weakSelf = self;
    // 使用方法 2，以 UIWindow 的形式显示到界面上，这种无需默认隐藏，也无需 add 到某个 UIView 上
    self.popupByWindow = [[QMUIPopupMenuView alloc] init];
    self.popupByWindow.automaticallyHidesWhenUserTap = YES;// 点击空白地方消失浮层
    [self.popupByWindow setPreferLayoutDirection:QMUIPopupContainerViewLayoutDirectionBelow];
    self.popupByWindow.maskViewBackgroundColor = UIColorMaskWhite;// 使用方法 2 并且打开了 automaticallyHidesWhenUserTap 的情况下，可以修改背景遮罩的颜色
    self.popupByWindow.shouldShowItemSeparator = YES;
    self.popupByWindow.itemConfigurationHandler = ^(QMUIPopupMenuView *aMenuView, QMUIPopupMenuButtonItem *aItem, NSInteger section, NSInteger index) {
        // 利用 itemConfigurationHandler 批量设置所有 item 的样式
        aItem.button.highlightedBackgroundColor = [UIColor.qd_tintColor colorWithAlphaComponent:.2];
        [aItem.button setTitleColor:appMainColor forState:UIControlStateNormal];
    };
   
    self.popupByWindow.didHideBlock = ^(BOOL hidesByUserTap) {
        //        [weakSelf.shebei_caidan_btn setTitle:@"显示菜单浮层" forState:UIControlStateNormal];
    };
    self.popupByWindow.sourceView = self.shebei_caidan_btn;// 相对于 button4 布局
    
    
    
 
    
    UIImageView *bgIv = [[UIImageView alloc] initWithFrame:CGRectMake(kLeftInset, CGRectGetMaxY(_shebei_caidan_btn.frame) + 10, ScreenWidth - 2 * kLeftInset, (ScreenWidth - 2 * kLeftInset) * 160 / 343.0)];
    [sv addSubview:bgIv];
    bgIv.image = UIImageMake(@"main_date_panel");
    bgIv.layer.cornerRadius = 20;
    bgIv.layer.masksToBounds = YES;
    bgIv.userInteractionEnabled = YES;
    
    self.dayPicker = [[ASDayPicker alloc] initWithFrame:CGRectMake(bgIv.mj_x + 10, bgIv.mj_y + (bgIv.mj_h - 72) * 0.5, bgIv.mj_w - 20, 72)];
    [self.sv addSubview:self.dayPicker];
//    self.dayPicker.backgroundColor = UIColor.redColor;
    // Allow picking from today until 4 weeks from now
    NSDateComponents *fourWeeks = [[NSDateComponents alloc] init];
    fourWeeks.day = 6 ;
    NSDate *endDate = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]dateByAddingComponents:fourWeeks toDate:[NSDate date] options:0];
    self.dayPicker.selectedDateBackgroundImage = [UIImage imageNamed:@"selection"];
    [self.dayPicker setStartDate:[NSDate date] endDate:endDate];
    [self.dayPicker addObserver:self forKeyPath:@"selectedDate" options:NSKeyValueObservingOptionInitial|NSKeyValueObservingOptionNew context:nil];
    
    // 显示月份
    UILabel *yuelb = UILabel.new;
    yuelb.frame = CGRectMake(bgIv.mj_x + 20, bgIv.mj_y + 14, 100, 30);
//    yuelb.font = UIFontMake(22);
    [self.sv addSubview:yuelb];
    self.yuelb = yuelb;
    
    // 显示事项
    UILabel *shijianlb = UILabel.new;
//    [self.sv addSubview:shijianlb];
    self.shijianlb = shijianlb;
    shijianlb.textColor = appMainColor;
    shijianlb.frame = CGRectMake(yuelb.mj_x, CGRectGetMaxY(self.dayPicker.frame)-8, ScreenWidth - yuelb.mj_x - 30, 40);
//    shijianlb.backgroundColor  = UIColor.redColor;
    
    // 添加 纵向 跑马灯
    [self addVerticalMarquee];
    
    
    UIButton *addshijianbtn = UIButton.new;
    [self.sv addSubview:addshijianbtn];
    addshijianbtn.frame = CGRectMake(ScreenWidth - 70 - 30, yuelb.mj_y-10, 70, 44);
    [addshijianbtn addTarget:self action:@selector(addshijianAction) forControlEvents:UIControlEventTouchUpInside];
    [addshijianbtn setImage:UIImageMake(@"main_add_icon") forState:UIControlStateNormal];
    
    NSArray *tt = @[@"温度\n---\n24℃", @"湿度\n---\n24%"];
    NSArray *tt_zhi = @[@"24", @"24"];
    NSArray *tt_bg = @[@"main_temperature_panel", @"main_humidity_panel"];
    NSArray *tt_img = @[@"main_temperature_icon", @"main_humidity_icon"];
    
    for (NSInteger i = 0; i < tt.count; i++) {
        UIImageView *bg = UIImageView.new;
        [self.sv addSubview:bg];
        bg.frame = CGRectMake(i *((SCREEN_WIDTH - 30) * 0.5 ) + (i+1) * 10, CGRectGetMaxY(bgIv.frame) + 10, (SCREEN_WIDTH - 30) * 0.5, (SCREEN_WIDTH - 30) * 0.5 *100 /165);
        bg.image = UIImageMake(tt_bg[i]);
        
        UIImageView *iv = UIImageView.new;
        [bg addSubview:iv];
        iv.image = UIImageMake(tt_img[i]);
        
        
        UILabel *l = UILabel.new;
        [bg addSubview:l];
        l.text = tt[i];
        l.font = UIFontMake(15);
        l.numberOfLines = 0;
        l.textColor = UIColor.whiteColor;
        l.frame = CGRectMake(20, 0, bg.mj_w * 0.5, bg.mj_h);
        if (i == 0) {
            iv.frame = CGRectMake(bg.mj_w - 52 - 10, (bg.mj_h - 44) * 0.5, 52, 44);
            self.cwgwendu_lb = l;
        }else{
            iv.frame = CGRectMake(bg.mj_w - 42 - 10, (bg.mj_h - 42) * 0.5, 42, 42);
            self.shidu_lb = l;
        }
    }
    
    UIView *v1_v = [[UIView alloc] initWithFrame:CGRectMake(kLeftInset, (SCREEN_WIDTH - 30) * 0.5 *100 /165 + CGRectGetMaxY(bgIv.frame) + 10 + kLeftInset, 4, 16)];
    [sv addSubview:v1_v];
    
    v1_v.layer.masksToBounds = YES;
    v1_v.layer.cornerRadius = 2;
    v1_v.backgroundColor = themeColor;
    
    UILabel *v1_lb = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(v1_v.frame) + 10, CGRectGetMinY(v1_v.frame), 100,30)];
    v1_lb.center = CGPointMake(v1_lb.center.x, v1_v.center.y);
    [sv addSubview:v1_lb];
    //
    NSMutableAttributedString *v1_lb_attr_str = [[NSMutableAttributedString alloc] initWithString:@"宠物呵护"];
    [v1_lb_attr_str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"PingFang-SC-Medium" size:17.0f] range:NSMakeRange(0, 4)];
    [v1_lb_attr_str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:17.0f/255.0f green:17.0f/255.0f blue:17.0f/255.0f alpha:1.0f] range:NSMakeRange(0, 4)];
    v1_lb.attributedText = v1_lb_attr_str;
    
    
    UILabel *shuimian_shichang_lb = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(v1_lb.frame), CGRectGetMinY(v1_lb.frame), ScreenWidth - kLeftInset - CGRectGetMaxX(v1_lb.frame), v1_lb.mj_h)];
    [sv addSubview:shuimian_shichang_lb];
    self.shuimian_shichang_lb = shuimian_shichang_lb;
    shuimian_shichang_lb.font = [UIFont systemFontOfSize:14];
    shuimian_shichang_lb.textColor = rgb(153,153,153);
//    shuimian_shichang_lb.text = @"近24小时睡眠时间：";
    [shuimian_shichang_lb setTextAlignment:NSTextAlignmentRight];
    
    
    
    self.gridView = [[QMUIGridView alloc] init];
    self.gridView.columnCount = 2;
    self.gridView.rowHeight = 100;
    self.gridView.separatorWidth = 10;
    self.gridView.separatorColor = self.view.backgroundColor;
//    self.view.backgroundColor = UIColorSeparator;
    self.gridView.separatorDashed = NO;
    [self.sv addSubview:self.gridView];
    
    // 将要布局的 item 以 addSubview: 的方式添加进去即可自动布局
    NSArray *imgNameArr = @[@"main_ws_icon", @"main_xd_icon"];
    
    for (NSInteger i = 0; i < imgNameArr.count; i++) {
        Gailan_grid_sub_view *view = [[Gailan_grid_sub_view alloc] initWithFrame:CGRectMake(0, 0, (ScreenWidth - 2 * kLeftInset - 10) * 0.5, 100)];
        view.layer.masksToBounds = YES;
        view.layer.cornerRadius = 5;
        view.iv.image = UIImageMake(imgNameArr[i]);
        
        view.backgroundColor = UIColor.whiteColor;
        [self.gridView addSubview:view];
    }
    
    self.gridView.frame = CGRectMake(kLeftInset, CGRectGetMaxY(shuimian_shichang_lb.frame) + 10, ScreenWidth - 2 * kLeftInset, QMUIViewSelfSizingHeight);
    
    
    UIView *v2_v = [[UIView alloc] initWithFrame:CGRectMake(kLeftInset, CGRectGetMaxY(self.gridView.frame) + kLeftInset, 4, 16)];
    [sv addSubview:v2_v];
    
    v2_v.layer.masksToBounds = YES;
    v2_v.layer.cornerRadius = 2;
    v2_v.backgroundColor = themeColor;
    
    UILabel *v2_lb = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(v2_v.frame) + 10, CGRectGetMinY(v2_v.frame), 100,30)];
    v2_lb.center = CGPointMake(v2_lb.center.x, v2_v.center.y);
    [sv addSubview:v2_lb];
    //
    NSMutableAttributedString *v2_lb_attr_str = [[NSMutableAttributedString alloc] initWithString:@"温馨提示"];
    [v2_lb_attr_str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"PingFang-SC-Medium" size:17.0f] range:NSMakeRange(0, 4)];
    [v2_lb_attr_str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:17.0f/255.0f green:17.0f/255.0f blue:17.0f/255.0f alpha:1.0f] range:NSMakeRange(0, 4)];
    v2_lb.attributedText = v2_lb_attr_str;
    
    self.wenxintishiLb = [[QMUILabel alloc] init];
    self.wenxintishiLb.backgroundColor = UIColor.whiteColor;
    self.wenxintishiLb.font = [UIFont systemFontOfSize:14];
    [sv addSubview:self.wenxintishiLb];
    self.wenxintishiLb.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 16, 16);
    self.wenxintishiLb.numberOfLines = 0;
    self.wenxintishiLb.layer.masksToBounds = YES;
    self.wenxintishiLb.layer.cornerRadius = 10;
    self.wenxintishiLb.text = @"";
    
}
#pragma mark 纵向 跑马灯



/** 添加纵向 跑马灯 */
- (void)addVerticalMarquee {
    self.verticalMarquee = [[JhtVerticalMarquee alloc]  initWithFrame:self.shijianlb.frame];
    self.verticalMarquee.backgroundColor = UIColor.clearColor;
    self.verticalMarquee.tag = 101;
    //        _verticalMarquee.isCounterclockwise = YES;
    self.verticalMarquee.numberOfLines = 0;
//    self.verticalMarquee.backgroundColor = [UIColor whiteColor];
    self.verticalMarquee.textColor = appMainColor;
    self.verticalMarquee.textAlignment = NSTextAlignmentLeft;
    self.verticalMarquee.scrollDelay = 3;
    self.verticalMarquee.textFont = [UIFont systemFontOfSize:15];
    [self.sv addSubview:self.verticalMarquee];
    
    [self.verticalMarquee scrollWithCallbackBlock:^(JhtVerticalMarquee *view, NSInteger currentIndex) {
        //        DLog(@"滚动到第 %ld 条数据", (long)currentIndex);
    }];
    
    
    NSArray *soureArray = @[@"尽量使手机、设备、Wi-Fi相互靠近",
                            @"请确保Wi-Fi信号良好",
                            @"请确认Wi-Fi密码正确"];
    
    //    self.verticalMarquee.isCounterclockwise = YES;
    self.verticalMarquee.sourceArray = soureArray;
    
    // 开始滚动
    [self.verticalMarquee marqueeOfSettingWithState:MarqueeStart_V];
}
- (void)qu_geng_xin_btn_action{
    
    Jiankang_fenxi_vc *vc= [[Jiankang_fenxi_vc alloc]init];
    vc.lastPage_bmi = self.current_bmi;
    vc.hidesBottomBarWhenPushed = YES;
    
    
    vc.deviceId = self.currentDevice.device_id;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)handleButtonEvent:(QMUIButton *)button {
    [self.popupByWindow showWithAnimated:YES];
  
}
- (void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    
}
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDefault;
}
#pragma mark - ================== 调试用 ==================
- (void)xxx_action{
    Huati_taolun_fabu_vc *vc= [[Huati_taolun_fabu_vc alloc]init];
    vc.title = @"发布话题讨论";
    
    
    vc= [[Huati_guangchang_vc alloc]init];
    
    vc = Tuijian_vc.new;
    
    //    vc = Tiezi_fabu_vc.new;
    vc = Tiezi_xiangqing_vc.new;
    
    vc= [[Tiezi_pinglun_vc alloc]init];
    
    
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //    [self xxx_action];
}

#pragma mark - ================== 宝宝几个月计算 ==================
- (NSString *)bb_month{
    //创建两个日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *startDate = [dateFormatter dateFromString:self.current_bmi.data.birthday];
    
    
    
    NSDate *endDate = [dateFormatter dateFromString:[self getCurrentDate]];
    
    //利用NSCalendar比较日期的差异
    NSCalendar *calendar = [NSCalendar currentCalendar];
    /**
     * 要比较的时间单位,常用如下,可以同时传：
     *    NSCalendarUnitDay : 天
     *    NSCalendarUnitYear : 年
     *    NSCalendarUnitMonth : 月
     *    NSCalendarUnitHour : 时
     *    NSCalendarUnitMinute : 分
     *    NSCalendarUnitSecond : 秒
     */
    NSCalendarUnit unit = NSCalendarUnitDay | NSCalendarUnitMonth;//只比较天数差异
    //比较的结果是NSDateComponents类对象
    NSDateComponents *delta = [calendar components:unit fromDate:startDate toDate:endDate options:0];
    //打印
    NSLog(@"%@",delta);
    //获取其中的"天"
    NSLog(@"%ld",delta.month);
    
    if (delta.month == 0) {
        return [NSString stringWithFormat:@"%ld天", delta.day];
    }
    return [NSString stringWithFormat:@"%ld个月", delta.month];
}
//获取当前时间
-(NSString *)getCurrentDate{
    NSDate * date = [NSDate date];
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init ];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString * dateStr = [dateFormatter stringFromDate:date];
    return dateStr;
}
- (NSAttributedString *)bb_title:(NSString *)raw_bb_title font:(UIFont *)font{
    NSMutableAttributedString *bb_title = [[NSMutableAttributedString alloc] initWithString:raw_bb_title];
    [bb_title addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, raw_bb_title.length)];
    [bb_title addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:255.0f/255.0f green:255.0f/255.0f blue:255.0f/255.0f alpha:1.0f] range:NSMakeRange(0, raw_bb_title.length)];
    return bb_title;
}
- (QMUIButton *)add_device_btn{
    if(_add_device_btn == nil)
    {
        _add_device_btn = [QDUIHelper generateLightBorderedButton];
        [_add_device_btn addTarget:self action:@selector(add_action) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _add_device_btn;
}

- (void)add_action{
    if ([self.bb_xq_lb.text isEqualToString:@"您还未添加设备"]) {
        // 添加设备
        CYLPlusDemoChildViewController *vc= [[CYLPlusDemoChildViewController alloc]init];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([self.bb_xq_lb.text isEqualToString:@"您的宝宝基本信息还未添加，为更好掌握宝宝健康状况，请及时添加！"]){
        // 添加bmi
        Jiankang_fenxi_vc *vc= [[Jiankang_fenxi_vc alloc]init];
        vc.hidesBottomBarWhenPushed = YES;
        
        vc.delegate = self;
        vc.deviceId = self.currentDevice.device_id;
        [self.navigationController pushViewController:vc animated:YES];
        
    }
}
- (void)updateWithBmiInfo:(Bmi_setBabyBmi *)info{
    self.current_bmi = info;
}
@end
